package com.linko.intelligent.common.filter;

import com.google.gson.Gson;
import com.linko.intelligent.base.UserInfo;
import com.linko.intelligent.common.config.StringRedisOperator;
import com.linko.intelligent.common.handler.TokenAuthticationFailHandler;
import com.linko.intelligent.common.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@Slf4j
class UserInfoFilterConfig {

    private static final PathMatcher pathMatcher = new AntPathMatcher();
    @Resource
    private StringRedisOperator stringRedisOperator;
    @Autowired
    private Gson gson;
    private TokenAuthticationFailHandler tokenAuthticationFailHandler = new TokenAuthticationFailHandler();

    @Bean
    public OncePerRequestFilter userInfoFilter() {
        return new OncePerRequestFilter() {

            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
                if (true || isProtectedUrl(request)) {
                    chain.doFilter(request, response);
                    return;
                }
                String token = request.getHeader("Authorization");
                String apiToken = request.getHeader("AuthorizationUserInfo");
                if (StringUtils.isBlank(token)) {
                    token = apiToken;
                }
                if (StringUtils.isBlank(token)) {
                    tokenAuthticationFailHandler.onNoAuthentication(request, response);
                    return;
                }
                String o = stringRedisOperator.get(token);

                if (o == null) {
                    tokenAuthticationFailHandler.onAuthenticationFailure(request, response, new Exception("身份认证失败"));
                    return;
                }
                UserInfo info = gson.fromJson(o, UserInfo.class);
//                UserInfo info = new UserInfo();
//                info.setId(1001L);
//                info.setName("wang");
                UserContext.setUserSession(info);

                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                response.setContentType("application/json;charset=UTF-8");
                chain.doFilter(request, response);
            }

            private boolean isProtectedUrl(HttpServletRequest request) {
                String path = request.getServletPath();
                return pathMatcher.match("/image/**", path)
                        || pathMatcher.match("/static/**", path)
                        || pathMatcher.match("/service/**", path)
                        || pathMatcher.match("/configuration/ui", path)
                        || pathMatcher.match("/configuration/security", path)
                        || pathMatcher.match("/webjars/**", path)
                        || pathMatcher.match("/favicon.ico", path)
                        || pathMatcher.match("/**/swagger-ui/**", path)
                        || pathMatcher.match("/**/swagger-ui.html", path)
                        || pathMatcher.match("/**/v2/**", path)
                        || pathMatcher.match("/**/v3/**", path)
                        || pathMatcher.match("/**/swagger-resources/**", path)
                        || pathMatcher.match("/login/auth", path)
                        || pathMatcher.match("/login/logout", path)
                        || pathMatcher.match("/c_login/**", path)
                        || pathMatcher.match("/mall/share/**", path)
                        || pathMatcher.match("/**/loginByPhone/**", path)
                        || pathMatcher.match("/send/sendMessage/**", path)
                        || pathMatcher.match("/**/mq_url/**", path)
                        || pathMatcher.match("/**/mqtt/**", path)
                        || pathMatcher.match("/**/customer/queryIdList/**", path)
                        || pathMatcher.match("/**/saveWeekForm/**", path)
                        || pathMatcher.match("/**/saveMonthForm/**", path)
                        || pathMatcher.match("/**/sms/**", path)
                        || pathMatcher.match("/**/oss/**", path)
                        || pathMatcher.match("/remote/**", path)
                        || pathMatcher.match("/user/login", path)
                        || pathMatcher.match("/user/list", path)
                        || pathMatcher.match("/attach/**", path)
                        ;
            }

        };
    }

}
